package com.jrx.anytxn.reporting.job.unionFile.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.AnyTxnBatchProperties;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.job.unionFile.step.RepayPlanFileProcessor;
import com.jrx.anytxn.reporting.job.unionFile.step.RepayPlanFileReader;
import com.jrx.anytxn.reporting.job.unionFile.step.RepayPlanFileWriter;
import com.jrx.anytxn.reporting.job.unionFile.step.UnionRepayPlanFileListener;
import com.jrx.anytxn.transaction.entity.AmRepaymentPlanInfo;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;

/**
 * 生成还款计划文件(增量抽取)
 * lbz
 */
@Configuration
@EnableConfigurationProperties(AnyTxnBatchProperties.class)
@EnableBatchProcessing
public class GenerateRepayPlanFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(GenerateRepayPlanFileConfiguration.class);


    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private UnionRepayPlanFileListener unionRepayPlanFileListener;
    @Autowired
    private AnyTxnBatchProperties anyTxnBatchProperties;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;
    @Autowired
    private RepayPlanFileProcessor repayPlanFileProcessor;
    @Autowired
    private RepayPlanFileWriter repayPlanFileWriter;

    @Bean
    public Job generateRepayPlanFileJob() {
        return jobBuilderFactory.get("generateRepayPlanFileJob").incrementer(new RunIdIncrementer()).listener(unionRepayPlanFileListener)
                .start(generateRepayPlanFileStep())
                .build();
    }

    @Bean
    public Step generateRepayPlanFileStep(){
        return stepBuilderFactory.get("generateRepayPlanFileStep")
                .<AmRepaymentPlanInfo, String>chunk(anyTxnBatchProperties.getFileConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(repayPlanFileReader())
                .processor(repayPlanFileProcessor)
                .writer(repayPlanFileWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getFileConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public MyBatisPagingItemReader<AmRepaymentPlanInfo> repayPlanFileReader() {
        logger.info("生成联盟还款计划批量启动,机构号：{}", ReportingConstant.DEFAULT_ORG_NUMBER);
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);

        BtBatchStatus statuses = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2,
                ReportingConstant.CUTOVER_END,org.getTenantId(),org.getToday());
        String startTime = null;
        if(null != statuses){
            startTime = DateUtils.format(statuses.getCreateTime(),"yyyy-MM-dd HH:mm:ss");
        }

        return new RepayPlanFileReader(sqlSessionFactory,anyTxnBatchProperties.getFileConfig().getPageSize(),startTime);
    }
}
